package com.lwx.chapter9;


/**
 * 线段树(区间树)
 * 为什么使用线段树
 *      区间染色问题
 *      区间查询 【i,j】之间的最大值，最小值，总和
 *      区间里的数据不断更新，更新一个元素，或者一个区间的值，跟新之后再查询
 *      使用数组来实现，有n个元素，则需要4n个空间
 */
public class SegmentTree<E> {
    private E[] data;
    private E[] tree;
    private Merger<E> merger;
    public SegmentTree(E[] arr , Merger<E> merger){
        this.merger = merger;
        data = (E[])new Object[arr.length];
        for (int i = 0; i < arr.length; i++) {
            data[i] = arr[i];
        }
        tree = (E[])new Object[4 * arr.length];
        buildSegmentTree(0,0, arr.length-1);
    }

    //在treeIndex的位置创建表示区间[l...r]的线段树
    private void buildSegmentTree(int treeIndex, int l, int r){
        if(l == r){
            tree[treeIndex] = data[l];
            return;
        }
        int leftIndex = leftChild(treeIndex);
        int rightIndex = rightChild(treeIndex);
        //不适用mid=(r+l)/2,是防止r+l超过整数的最大值
        int mid = l + (r - l)/2;
        buildSegmentTree(leftIndex, l , mid);
        buildSegmentTree(rightIndex, mid+1, r);

        tree[treeIndex] = merger.merge(tree[leftIndex] , tree[rightIndex]);
    }

    public int getSize(){
        return data.length;
    }

    /**
     * 获取完全二叉树的左孩子索引
     * @param index
     * @return
     */
    public int leftChild(int index){
        return  2*index + 1;
    }

    /**
     * 获取完全二叉树的右孩子索引
     * @param index
     * @return
     */
    public int rightChild(int index){
        return  2*index + 2;
    }

    public E get(int index){
        if(index < 0 || index >= data.length){
            throw new IllegalArgumentException("Index is out of bound.Index should not less than zero or bigger than the lenght of data");
        }
        return data[index];
    }

    public E query(int queryL, int queryR){
        if(queryL < 0 || queryL > data.length-1 ||queryR < 0 || queryR > data.length-1 || queryL > queryR){
            throw new IllegalArgumentException("queryL or queryR is out of bound.Index should not less than zero or bigger than the lenght of data");
        }
        return query(0, 0, data.length-1, queryL, queryR);
    }

    //在以treeIndex为根的线段树, 表示的区间为[l...r]的范围里，搜索区间[queryL...queryR]
    //可以在tree中增加一个节点，有l\r,表示以treeIndex这个节点，代表的是区间[l...r]之间的操作后的值
    private E query(int treeIndex, int l, int r, int queryL, int queryR){
        if(queryL == l && queryR == r){
            return tree[treeIndex];
        }
        int mid = l + (r - l)/2;
        int leftIndex = leftChild(treeIndex);
        int rightIndex = rightChild(treeIndex);

        if(queryL >= mid + 1){
            //只查询右子树
            return query(rightIndex , mid+1 , r , queryL , queryR);
        }else if(queryR <= mid){
            //只查询左子树
            return query(leftIndex , l , mid , queryL , queryR);
        }else {
            //左右子树都查询
            return merger.merge(query(leftIndex , l , mid, queryL , mid), query(rightIndex , mid + 1, r , mid+1 , queryR));
        }

    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append('[');
        for (int i = 0; i < tree.length; i++) {
            if(tree[i] != null){
                res.append(tree[i]);
            }else {
                res.append("null");
            }
            if(i != tree.length -1){
                res.append(',');
            }else {
                res.append(']');
            }
        }
        return res.toString();
    }
}
